package com.cloudfast.config;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;

import com.cloudfast.context.CloudSecurity;

@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Autowired
    private CloudSecurity cloudSecurity;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        List<String> whiteList = cloudSecurity.getWhiteList();
        if (whiteList == null) {
            whiteList = new ArrayList<>();
        }
        String[] whiteListMethod = new String[whiteList.size()];
        for (int i = 0; i < whiteList.size(); i++) {
            whiteListMethod[i] = whiteList.get(i);
        }
        http.authorizeRequests().antMatchers(whiteListMethod).permitAll()// 匿名访问配置
                .antMatchers("/**").authenticated()// 配置order访问控制，必须认证后才可以访问
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll().anyRequest().authenticated();// 其他的必须验证才可以访问

    }

}
